<?php
class Articles extends Model
{
	function __construct()
	{
		parent::Model();
	}

	function get_query ($sql)
	{
		$this->db->cache_off();
		$query = $this->db->query($sql);
		return $query->result();
	}
	function execute_query ($sql)
	{
		$query = $this->db->query($sql);
	}
	function get_channels ()
	{
		return $this->get_query("SELECT * FROM om_channels ORDER BY sortorder ASC");
		
	}
	function get_blocks ($channel = NULL)
	{
		if ($channel != NULL)
		{
			return $this->get_query("SELECT * FROM om_blocks WHERE channel = {$channel} ORDER BY sortorder ASC");
		}
		else
		{
			return $this->get_query("SELECT * FROM om_blocks ORDER BY sortorder ASC");
		}
	}
	
	function get_newsstream ($block)
	{
		return $this->get_query("SELECT * FROM om_newsstream WHERE block = {$block} ORDER BY sortorder ASC");
	}
	function get_article ($id)
	{
		$ret = array();
		foreach ($this->get_query("SELECT * FROM om_articles WHERE id = {$id}") as $a)
		{
			$ret = toArray($a);
		}
		
		return $ret;
	}
	function get_sources ($block_id)
	{
		$ret = array();
		
		$sources = $this->get_query("SELECT * FROM om_sources WHERE block_id = {$block_id}");
		
		foreach ($sources as $s)
		{
			$q = $this->get_query($s->sql);
			$ret[$s->machine_name] = toArray($q);
		}
		
		return $ret;
	}
	function get_tree ()
	{
		$channels = $this->get_channels();
		$ret = array();
		foreach ($channels as $c)
		{
			$ret[$c->machine_name] = array('blocks' => array());
			$blocks = $this->get_blocks($c->id);
			
			foreach ($blocks as $b)
			{
				$block = array ('type' => $b->type, 'newsstream' => array(), 'custom_block' => $b->custom_block, 'article_block' => $b->article_block, 'sources' => array());
				$sources = $this->get_sources($b->id);
				$block['sources'] = $sources;
				if ($b->type == 'newsstream')
				{
					//$ret[$c->machine_name]['blocks']['newsstream'] = $this->get_newsstream($b->id);
					foreach ($this->get_newsstream($b->id) as $n)
					{
						$block['newsstream'][] = array(
							'type' => $n->type,
							'article_content' => $this->get_article($n->article_id)
						);
					}
				}
				
				$ret[$c->machine_name]['blocks'][] = $block;
			}
		}
		
		return $ret;
	}
	function get_menu ()
	{
		
		$query = $this->get_query("SELECT * FROM om_sections ORDER BY sortorder ASC");
		$ret = array();
		foreach ($query as $row)
		{
			$ret[$row->machine_name] = array ('title' => $row->name, 'selected' => false);
		}
		return $ret;
		/*
		return array(
			'inrikes' => array('title' => 'Inrikes', 'selected' => false),
			'utrikes' => array('title' => 'Utrikes', 'selected' => false),
			'sport' => array('title' => 'Sport', 'selected' => false)
		);
		*/
	}
}
?>